package com.inhim.pjhim.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.inhim.pjhim.R;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.fragment.CollectionFragment;
import com.inhim.pjhim.fragment.CollectionRadioFragment;
import com.inhim.pjhim.fragment.CollectionReadFragment;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.view.BToast;
import com.inhim.pjhim.view.CenterDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Request;

public class CollectionNewActivity extends BaseActivity implements View.OnClickListener {
    private ImageView iv_back;
    private Map vipCollectionIdsMap;
    private CenterDialog centerDialog;
    private ViewPager viewPager;
    private ArrayList<Fragment> fs;
    private RadioButton radio1, radio2, radio3;
    private TextView tv_cancel, tv_delete;
    private CheckBox checkbox;
    CollectionFragment historyFragment1;
    CollectionRadioFragment historyFragment2;
    CollectionReadFragment historyFragment3;
    MyPagerAdapter adapter;
    private LinearLayout lin_clear;

    @Override
    public Object offerLayout() {
        return R.layout.activity_collection_new;
    }

    @Override
    public void onBindView() {
        initView();
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        vipCollectionIdsMap = new HashMap();
        setFragment();
    }

    private void setFragment() {
        Bundle bundle1 = new Bundle();
        bundle1.putSerializable("Type", "2");
        Bundle bundle2 = new Bundle();
        bundle2.putSerializable("Type", "3");
        Bundle bundle3 = new Bundle();
        bundle3.putSerializable("Type", "1");
        historyFragment1 = new CollectionFragment();
        historyFragment2 = new CollectionRadioFragment();
        historyFragment3 = new CollectionReadFragment();
        historyFragment1.setArguments(bundle1);
        historyFragment2.setArguments(bundle2);
        historyFragment3.setArguments(bundle3);
        fs = new ArrayList<>();
        fs.add(historyFragment1);
        fs.add(historyFragment2);
        fs.add(historyFragment3);
        FragmentManager fm = getSupportFragmentManager();
        adapter = new MyPagerAdapter(fm);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(3);
        setListener();
    }

    private void setListener() {
        // TODO Auto-generated method stub
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        radio1.setChecked(true);
                        break;
                    case 1:
                        radio2.setChecked(true);
                        break;
                }

            }

            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    private void initView() {
        lin_clear = findViewById(R.id.lin_clear);
        viewPager = findViewById(R.id.viewPager);
        radio1 = findViewById(R.id.radio1);
        radio2 = findViewById(R.id.radio2);
        radio3 = findViewById(R.id.radio3);
        radio1.setOnClickListener(this);
        radio2.setOnClickListener(this);
        radio3.setOnClickListener(this);
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_delete = findViewById(R.id.tv_delete);
        tv_cancel.setOnClickListener(this);
        tv_delete.setOnClickListener(this);
        checkbox = findViewById(R.id.checkbox);
        checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (historyFragment1 != null) {
                if(radio1.isChecked()){
                    historyFragment1.setAllSelect(isChecked);
                }else if(radio2.isChecked()){
                    historyFragment2.setAllSelect(isChecked);
                }else if(radio3.isChecked()){
                    historyFragment3.setAllSelect(isChecked);
                }
            }
        });
    }

    /**
     * 自定义适配器  FragmentPagerAdapter
     */
    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            return fs.get(arg0);
        }

        @Override
        public int getCount() {
            return fs.size();
        }
    }

    @Override
    public void destory() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.radio1:
                viewPager.setCurrentItem(0);
                break;
            case R.id.radio2:
                viewPager.setCurrentItem(1);
                break;
            case R.id.radio3:
                viewPager.setCurrentItem(2);
                break;
            case R.id.tv_cancel:
                if (historyFragment1 != null) {
                    if(radio1.isChecked()){
                        historyFragment1.onCancel();
                    }else if(radio2.isChecked()){
                        historyFragment2.onCancel();
                    }else if(radio3.isChecked()){
                        historyFragment3.onCancel();
                    }
                }
                break;
            case R.id.tv_delete:
                setDiaglog();
                break;
            default:
                break;
        }
    }

    private void setDiaglog() {
        if (centerDialog == null) {
            View outerView = LayoutInflater.from(CollectionNewActivity.this).inflate(R.layout.dialog_deletes, null);
            Button btn_ok = outerView.findViewById(R.id.btn_ok);
            Button btn_cancel = outerView.findViewById(R.id.btn_cancel);
            TextView tv_title = outerView.findViewById(R.id.tv_title);
            tv_title.setText("是否确认清空？");
            btn_ok.setOnClickListener(v -> {
                centerDialog.dismiss();
                if (checkbox.isChecked()) {
                    deleteAllHistory();
                } else {
                    deleteIdsHistory();
                }
            });
            btn_cancel.setOnClickListener(v -> centerDialog.dismiss());
            //防止弹出两个窗口
            if (centerDialog != null && centerDialog.isShowing()) {
                return;
            }

            centerDialog = new CenterDialog(CollectionNewActivity.this, R.style.ActionSheetDialogBotoomStyle);
            //将布局设置给Dialog
            centerDialog.setContentView(outerView);
        }
        centerDialog.show();//显示对话框
    }

    private void deleteAllHistory() {
        showLoading("删除中");
        FormBody.Builder formBody = new FormBody.Builder();
        MyOkHttpClient.getInstance().doDelete(Urls.deleteAllHistory(), formBody.build(), new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                BToast.showText("删除失败");
                hideLoading();
            }

            @Override
            public void onSuccess(Request request, String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getInt("code") == 0) {
                        //refresh=true;
                        //getHistoryList();
                        if (historyFragment1 != null) {
                            if(radio1.isChecked()){
                                historyFragment1.notify(true);
                            }else if(radio2.isChecked()){
                                historyFragment2.notify(true);
                            }else if(radio3.isChecked()){
                                historyFragment3.notify(true);
                            }
                        }
                    } else {
                        BToast.showText(jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void setAllCheck(boolean isCheck) {
        if (checkbox != null) {
            checkbox.setChecked(isCheck);
        }
    }

    private void deleteIdsHistory() {
        String ids = null;
        if (radio1.isChecked() && historyFragment1 != null) {
            ids = historyFragment1.getDeleteId();
        }
        if (radio2.isChecked() && historyFragment2 != null) {
            ids = historyFragment2.getDeleteId();
        }
        if (radio3.isChecked() && historyFragment3 != null) {
            ids = historyFragment3.getDeleteId();
        }
        if (ids == null || "".equals(ids)) {
            BToast.showText("请选择需要删除得数据");
            return;
        }
        showLoading("删除中");
        FormBody.Builder formBody = new FormBody.Builder();
        MyOkHttpClient.getInstance().doDelete(Urls.deleteIdsHistory(ids), formBody.build(), new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                BToast.showText("删除失败");
                hideLoading();
            }

            @Override
            public void onSuccess(Request request, String result) {
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getInt("code") == 0) {
                        if (historyFragment1 != null) {
                            if(radio1.isChecked()){
                                historyFragment1.notify(true);
                            }else if(radio2.isChecked()){
                                historyFragment2.notify(true);
                            }else if(radio3.isChecked()){
                                historyFragment3.notify(true);
                            }
                        }
                    } else {
                        BToast.showText(jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
